/* eslint-disable default-case */
import { message } from 'antd';
import {
  checkCreateChargeBillTask,
  getChargeProgress,
  getList,
  deleteBill,
  markCharge,
  singleExportFileNs,
  mergeExportFileNs,
  getUploadFileNs,
  getBillInfo,
  getTableList,
  downloadNsTemplate,
  getNotEnterList,
  getSuppIdDataList,
  getsendBillData,
  mergeBilling,
  generatBilling,
  createBilling,
  createBill,
  createNoEnterBill,
} from '@/services/chargemanage';
import * as service from '@/services/socket';

export default {
  state: {
    activeKey: '1',
    formFieldsValue: {},
    expandForm: false,
    isHasTask: false,
    billTaskId: null,
    taskCode: null,
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    noBillData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    modalVisible: false,
    showProgress: false,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '生成账单', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/nsApi/nsBillChrg/downBillException', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    valuesArr: [
      'sendSuppId',
      'billYm',
      'billState',
      'billNo',
    ]
  },
  effects: {
    *getList({ payload }, { call, put }) {
      const res = yield call(getList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        yield put({
          type: 'updateList',
          payload: {
            data: res.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(res.message);
      }
    },
    // 判断有无账单任务
    *checkCreateBillTask(_, { call, put }) {
      const response = yield call(checkCreateChargeBillTask);
      if (response.success && response.data) {
        if (response.data.taskCode === 3) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: true,
              billTaskId: response.data.billTaskId,
              taskCode: response.data.taskCode,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: false,
            },
          });
        }
      }
      return response;
    },
    // 标记已收费
    *markCharge({ payload }, { call }) {
      const res = yield call(markCharge, payload);
      return res;
    },

    // 获取进度数据
    *getProgress({ payload }, { call, put }) {
      const response = yield call(getChargeProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: { progressPercent: response.data.rate },
        });
      }
      return response;
    },

    // 删除账单
    *deleteBill({ payload }, { call }) {
      const response = yield call(deleteBill, payload);
      return response;
    },
    // 收费账单 详情 xxl
    *getBillInfo({ payload }, { call }) {
      const response = yield call(getBillInfo, payload);
      return response;
    },
    // 收费账单 详情表格明细
    *getTableList({ payload }, { call }) {
      const response = yield call(getTableList, payload);
      return response;
    },
    // 下载模板
    *updownfiles({ payload }, { call }) {
      const response = yield call(downloadNsTemplate, payload);
      return response;
    },
    // 全国 未进账单列表数据
    *getNotEnterList({ payload }, { call, put }) {
      const response = yield call(getNotEnterList, payload);
      yield put({
        type: 'getNotEnterListData',
        payload: {
          data: [],
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (response.success) {
        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        yield put({
          type: 'getNotEnterListData',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        yield put({
          type: 'getNotEnterListData',
          payload: {
            data: [],
            currentPage: 1,
            pageSize: 10,
          },
        });
        message.warning(response.message || '获取列表失败');
      }
    },
    // 账单单个下载
    *singleExport({ payload }, { call }) {
      const response = yield call(singleExportFileNs, payload);
      return response;
    },

    // 账单合并下载
    *mergeExport({ payload }, { call }) {
      const response = yield call(mergeExportFileNs, payload);
      return response;
    },

    // 全国 收费账单 - 账单下载
    *uploadFile({ payload }, { call }) {
      const response = yield call(getUploadFileNs, payload);
      return response;
    },

    // 获取签约方列表
    *getSuppIdList({ payload }, { call }) {
      const response = yield call(getSuppIdDataList, payload);
      return response;
    },

    // 发送签约方
    *sendBillData({ payload }, { call }) {
      const response = yield call(getsendBillData, payload);
      return response;
    },

    // 合并账单
    *mergeBill({ payload }, { call }) {
      const response = yield call(mergeBilling, payload);
      return response;
    },

    // 是否在未进账单生成
    *isTask({ payload }, { call }) {
      const response = yield call(generatBilling, payload);
      return response;
    },

    // 生成账单
    *createBill({ payload }, { call }) {
      const response = yield call(createBilling, payload);
      return response;
    },

    // 上传文件:批量进度:获取batchId后获取进度 :batchType：1为生成账单，2为合并账单,3/4:未进账单生成(enterActiveKey)
    *uploadFileWithProgress(
      {
        payload: { batchType, params },
      },
      { call, put }
    ) {
      let batchUrl = createBilling;
      switch (batchType) {
        case 1:
          batchUrl = createBilling;
          break;
        case 2:
          batchUrl = mergeBilling;
          break;
        case 3:
          batchUrl = createBill;
          break;
        case 4:
          batchUrl = createNoEnterBill;
          break;
        default:
          break;
      }
      const response = yield call(batchUrl, params);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            batchId: response.data && response.data.batchId,
            progressPercent: 0,
          },
        });
        if (batchType === 1 || batchType === 3 || batchType === 4) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: response.data && response.data.taskCode === 3,
            },
          });
          if (response.data.taskCode === 1) {
            if (response.data && response.data.successProp !== 100) {
              yield put({
                type: 'updateModelData',
                payload: {
                  modalVisible: false,
                  showProgress: true,
                },
              });
              yield call(service.socketChannel, {
                type: 'sub',
                data: {
                  to: response.data && (response.data.batchId || response.data),
                  type: 'nsBill',
                },
              });
            } else {
              yield put({
                type: 'updateBatchTask',
                payload: response.data,
              });
            }
          } else if (response.data.taskCode === 3) {
            message.warning('当前有账单任务正在生成，请稍后操作！');
          }
        } else if (batchType === 2) {
          if (response.data && response.data.successProp !== 100) {
            yield put({
              type: 'updateModelData',
              payload: {
                modalVisible: false,
                showProgress: true,
              },
            });
            yield call(service.socketChannel, {
              type: 'sub',
              data: {
                to: response.data && (response.data.batchId || response.data),
                type: 'nsBill',
              },
            });
          } else {
            yield put({
              type: 'updateBatchTask',
              payload: response.data,
            });
          }
        }
      } else {
        // 操作失败
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
    },
    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.chargebillns);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateBatchTask',
          payload,
        });
      }
    },
  },

  reducers: {
    updateList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },
    // 未进账单列表数据
    getNotEnterListData(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list =
        data && data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        noBillData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { resultInfo, modalVisible } = state;
      modalVisible = false;
      if (payload.successProp === 100) {
        if (payload.errorCount) {
          resultInfo.errorParams = {
            batchId: payload.batchId,
          };
          resultInfo.errorCount = payload.errorCount || 0;
        }
        resultInfo.taskCount = payload.taskNumber;
        resultInfo.billCount = payload.successCount;
        resultInfo.feeYm =
          payload.feeYm &&
          `${payload.feeYm.toString().substr(0, 4)}-${payload.feeYm.toString().substr(4, 5)}`;
        resultInfo.successCount = payload.successCount;
        resultInfo.taskFlag = payload.taskFlag || 1;
        resultInfo = { ...resultInfo, ...payload };
      }
      return {
        ...state,
        modalVisible,
        progressPercent: payload.successProp,
        resultInfo,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'nsBill':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
